package com.example.service;

import com.example.DTO.ShoppingCartDTO;
import com.example.entity.Product;
import com.example.entity.ShoppingCart;
import com.example.mapper.ShoppingCartMapper;
import com.example.result.Result;
import com.example.vo.ShoppingCartVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    //根据买家ID查询购物车里面的商品
    public Result selectShCartById(Integer buyerId) {
         List<ShoppingCartVO> shoppingCartVOList= shoppingCartMapper.selectShCartById(buyerId);
         if(shoppingCartVOList==null||shoppingCartVOList.isEmpty()){
             return Result.success().code(String.valueOf(200)).msg("购物车为空");
         }else{
             return Result.success(shoppingCartVOList);
         }
    }
    //批量删除购物车里面的商品
    public void delShoppingCartBatch(List<Integer> ids) {
         shoppingCartMapper.delShoppingCartBatch(ids);
    }
    //加入商品到购物车
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        //1.先判断该商品是否存在于购物车
        boolean exist=shoppingCartMapper.selectBybIdpId(shoppingCartDTO);
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUpdateTime(LocalDateTime.now());
        int amount=shoppingCartDTO.getAmount();
        if(!exist){
        //2.如果不存在，则新增一条数据，添加商品到购物车
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.addShoppingCart(shoppingCart,amount);
        }else{
        //3.如果存在，则更新这条数据，数量加amount，总价改变，更新时间改变
            shoppingCartMapper.updateShoppingCart(shoppingCart,amount);
        }
    }
}
